<template>
  <el-button plain type="primary" @click="openCreateRoleDialog"
    >添加角色</el-button
  >

  <el-table
    row-key="id"
    :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    style="width: 100%; margin-top: 30px"
    :header-cell-style="{
      background: '#f8f8f9',
      height: '60px',
      color: '#000000',
    }"
    :data="paginatedData"
  >
    <el-table-column prop="id" label="角色编号" width="100" />
    <el-table-column prop="roleName" label="角色名称" width="200" />
    <el-table-column prop="roleRoute" label="角色字符" width="200" />
    <el-table-column prop="createdAt" label="创建时间" width="300" />
    <el-table-column prop="updatedAt" label="更新时间" width="300" />
    <el-table-column prop="operate" label="操作">
      <template #default="scope">
        <el-button
          type="primary"
          size="small"
          @click="openUpdateMenuBtn(scope.row)"
          >编辑</el-button
        >

        <el-popconfirm
          title="你确定要删除吗?"
          @confirm="deleteRoleBtn(scope.row)"
        >
          <template #reference>
            <el-button type="danger" size="small">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>

  <div style="margin-top: 20px; display: flex; justify-content: flex-end">
    <el-pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableData.length"
      :page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      v-model:current-page="currentPage"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
    />
  </div>

  <CreateRoleDialog
    :menuList="menuList"
    :dialogFormVisible="createDialogFormVisible"
    @changeVisible="changeCreateFormVisible"
    @checkNodes="checkNodes"
    @submitRole="submitRole"
  ></CreateRoleDialog>

  <UpdateRoleDialog
    :menuList="menuList"
    :dialogFormVisible="updateDialogFormVisible"
    :updateDialogData="updateDialogData"
    @changeVisible="changeUpdateFormVisible"
    @updateNodes="updateNodes"
    @updateRole="updateRole"
  ></UpdateRoleDialog>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from "vue";
import { useRoleStore } from "@/stores/model/role";
import { useMenuStore } from "@/stores/model/menu";
import CreateRoleDialog from "./CreateRoleDialog.vue";
import UpdateRoleDialog from "./UpdateRoleDialog.vue";
import { ElMessage } from "element-plus";

const roleStore = useRoleStore();
const menuStore = useMenuStore();

// 分页相关的数据
const currentPage = ref(1);
const pageSize = ref(10);
const createDialogFormVisible = ref(false);
const updateDialogFormVisible = ref(false);

const tableData = ref([]);
const menuList = ref([]);
const createCheckedNodes = ref([]);
const updateCheckedNodes = ref([]);
const roleId = ref(-1);

let updateDialogData = reactive({});

const _dfs = (data) => {
  if (!data || !data.length) return [];
  return data.map((item) => {
    const children = _dfs(item.children);
    return {
      value: item.id,
      label: item.menuName,
      menuPath: item.menuPath,
      children: children.length > 0 ? children : [],
    };
  });
};

const init = async () => {
  let res = await roleStore.getRoleList(currentPage.value, pageSize.value);
  if (res) tableData.value = roleStore.roleList;
  res = await menuStore.getMenuList();
  if (res) menuList.value = _dfs(menuStore.menuList);
};

onMounted(async () => {
  await init();
});

const openCreateRoleDialog = () => {
  createDialogFormVisible.value = true;
};

const openUpdateMenuBtn = async (row) => {
  updateDialogData = row;
  roleId.value = row.id;
  const res = await roleStore.getRoleMenuByRoleId(row.id);
  if (res) {
    const checkedKeysArr = res.data.data;
    let checkedKeys = [];

    // 根据 menuList 提取叶子节点并且结合 checkedKeysArr 提取出 checkedKeys
    const extractLeafNodes = (data) => {
      let leafNodes = [];
      const dfs = (node) => {
        if (!node.children || node.children.length === 0) {
          leafNodes.push(node.value);
        } else {
          node.children.forEach((child) => dfs(child));
        }
      };
      data.forEach((item) => dfs(item));
      return leafNodes;
    };

    const leafNodes = extractLeafNodes(menuList.value);
    if (!checkedKeysArr.length !== 0) {
      //超级管理员默认全选
      if (roleId.value == 3) {
        checkedKeys = leafNodes;
      } else {
        checkedKeys = leafNodes.filter((key) => checkedKeysArr.includes(key));
      }
    }
    updateDialogData.checkedKeys = checkedKeys;
  }
  updateDialogFormVisible.value = true;
};

// 计算属性，用于获取当前页的数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value.slice(start, end);
});

// 处理页码变化的方法
const handlePageChange = async (newPage) => {
  currentPage.value = newPage;
  await init();
};

// 处理每页显示条数变化的方法
const handleSizeChange = async (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 当改变每页显示条数时，重置到第一页
  await init();
};

const changeCreateFormVisible = (data) => {
  createDialogFormVisible.value = data.newDialogFormVisible;
};

const changeUpdateFormVisible = (data) => {
  updateDialogFormVisible.value = data.newDialogFormVisible;
};

const checkNodes = ({ checkedKeys, allCheckedKeys }) => {
  const newData = new Set([
    ...allCheckedKeys.halfCheckedKeys,
    ...allCheckedKeys.checkedKeys,
  ]);

  createCheckedNodes.value = [...newData];
};

const updateNodes = ({ checkedKeys, allCheckedKeys }) => {
  const newData = new Set([
    ...allCheckedKeys.halfCheckedKeys,
    ...allCheckedKeys.checkedKeys,
  ]);

  updateCheckedNodes.value = [...newData];
};

const submitRole = async (form) => {
  console.log(createCheckedNodes.value);
  const roleData = {
    roleName: form.roleName,
    roleRoute: form.roleRoute,
    menuIds: createCheckedNodes.value,
  };
  const res = await roleStore.createRole(roleData);
  if (res) {
    createCheckedNodes.value = [];
    form.roleName = "";
    form.roleRoute = "";
    await init();
    createDialogFormVisible.value = false;
    ElMessage({
      message: "创建成功",
      type: "success",
    });
  }
};

const updateRole = async (form) => {
  const roleData = {
    roleName: form.roleName,
    roleRoute: form.roleRoute,
    menuIds: updateCheckedNodes.value,
  };

  const res = await roleStore.updateRole(roleId.value, roleData);
  if (res) {
    updateCheckedNodes.value = [];
    form.roleName = "";
    form.roleRoute = "";
    updateDialogFormVisible.value = false;
    ElMessage({
      message: "更新成功",
      type: "success",
    });
    await init();
  }
};

const deleteRoleBtn = async (row) => {
  const res = await roleStore.deleteRole(row.id);
  if (res) {
    ElMessage({
      message: "删除成功",
      type: "success",
    });
    await init();
  }
};
</script>
